package wsz.springboot;

import org.springframework.context.ApplicationContext;
import wsz.springboot.server.TomcatFactory;

import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;

/**
 * 核心启动类
 * @author wsz
 * @date 2021/11/8 14:45
 **/
public class SpringApplication {

    private Set<Class<?>> primarySources;

    public SpringApplication ( Class<?>... primarySources) {
        this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
    }

    /**
     * 启动方法
     * @param primarySource
     */
    public static SpringApplication run(Class<?> primarySource) {
        return new SpringApplication(new Class<?>[] {primarySource}).run();
    }

    /**
     *
     * @return
     */
    public SpringApplication run() {
        ApplicationContext context = null;
        // 1.获取并启动监听器
        getRunListeners();
        // 2.构造应用上下文环境
        prepareEnvironment();
        // 3.初始化应用上下文
        context = createApplicationContext();
        // 4.刷新应用上下文前的准备阶段
        prepareContext(context);
        // 5.刷新应用上下文
        refresh();
        // 6.刷新应用上下文后的扩展接口
        afterRefresh(context);

        return null;
    }

    private void afterRefresh(ApplicationContext context) {
    }

    private void refresh() {
        TomcatFactory serverFactory = new TomcatFactory();
        serverFactory.createWebServer();
    }

    private void prepareContext(ApplicationContext context) {
        //TODO 读取启动类的同层级包
        String scanPakage = "";
        for (Class t : this.primarySources) {
            scanPakage = t.getPackage().getName();
        }
        System.out.println(scanPakage);
    }

    private ApplicationContext createApplicationContext() {
        return null;
    }

    private void prepareEnvironment() {
    }

    private void getRunListeners() {
    }
}
